package com.zz.common.web;

import com.zz.common.annotation.Path;
import com.zz.common.annotation.Serialize;
import com.zz.common.config.Config;
import com.zz.common.protocol.ProtocolFactory;
import com.zz.common.serialize.SerializerDispatcher;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * web 处理器工厂
 */
@Slf4j
public class WebHandlerFactory {

    private final static Map<String, WebHandler> webHandlerCache = new ConcurrentHashMap<>();

    static {
        ServiceLoader<WebHandler> webHandlers = ServiceLoader.load(WebHandler.class);
        webHandlers.forEach(webHandler -> {
            Path path = webHandler.getClass().getAnnotation(Path.class);
            if (null == path || Objects.equals("", path.value())) {
                log.warn("{} 未配置 path", webHandler.getClass().getName());
                return;
            }
            if (!Objects.equals("", path.protocol()) && ProtocolFactory.getProtocolByConfig(path.protocol()) != Config.getInstance().getProtocol()) {
                return;
            }
            webHandlerCache.put(path.value(), webHandler);
        });
    }

    public static WebHandler getWebHandler(String path) {
        return webHandlerCache.get(path);
    }
}
